import axios from 'axios'
import { getToken, clearToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: '/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    const token = getToken()
    if (token) {
      if (!config.headers) {
        config.headers = {}
      }
      config.headers.token = token
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    // if (
    //   res.message === 'token 无效，请重新获取' ||
    //   res.message === '无 token ，请重新登陆'
    // ) {
    //   clearToken()
    //   Message.error('token无效，请重新登录')
    // }
    // if (
    //   res.code !== 20000 &&
    //   res.code !== 200 &&
    //   res.status !== '200' &&
    //   res.status !== null
    // ) {
    //   return Promise.reject(new Error(res.msg || '错误'))
    // }
    return res
  },
  (error) => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service